package com.hospital.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;

/**
 * 事务切面类
 *
 * @Author yuhuan
 * @Date 2022/4/2
 */
@Component
@Aspect
@Slf4j
public class TransactionAspect {
    @Autowired
    private DataSourceTransactionManager transactionManager;

    @Around("PointCutConcentrationCamp.toServiceOfDoctorTransactionMethod()")
    public Object weavingTestTransaction(ProceedingJoinPoint joinPoint) {
        Object value = null;
        // 开启事务
        TransactionStatus transaction = transactionManager.getTransaction(new DefaultTransactionAttribute());
        log.info("事务测试 ^ 开启事务");
        try {
            // 回调到通知链形成回调循环，直到通知栈执行完毕就会执行引用点
            value = joinPoint.proceed();
            transactionManager.commit(transaction);
            log.info("事务测试 ^ 事务已提交");
        } catch (Throwable throwable) {
            transactionManager.rollback(transaction);
            log.info("事务测试 ^ 出现未知错误！事务已回滚");
        }
        return value;
    }
}
